package com.uzhie.media;

import com.uzhie.media.bean.MediaMsgBean;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.apache.log4j.Logger;

import java.nio.charset.Charset;

/**
 * Created by TangFei on 2018/8/8.
 * 流媒体协议编码
 */
public class MediaByteEncoder extends MessageToByteEncoder<MediaMsgBean> {

    private Logger logger = Logger.getLogger(this.getClass());

    // 分隔符
    private byte[] delimiter;

    public MediaByteEncoder() {
    }

    public MediaByteEncoder(byte[] delimiter) {
        this.delimiter = delimiter;
    }

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, MediaMsgBean mediaMsgBean, ByteBuf byteBuf) throws Exception {
        logger.trace("enter method encode");
        byteBuf.writeBytes(delimiter);
        byteBuf.writeBytes(integerTo2Bytes(mediaMsgBean.getMsgID()));
        byte[] bodyBytes = mediaMsgBean.getMsgBody().toJSONString().getBytes(Charset.forName("GBK"));
        byte[] bodyLength = integerTo2Bytes(bodyBytes.length);
        byteBuf.writeBytes(bodyLength);
        byteBuf.writeBytes(bodyBytes);
        logger.info("响应消息ID：" + mediaMsgBean.getHexMsgID() + " 消息体：" + mediaMsgBean.getMsgBody());
        logger.info("响应字节：" + ByteBufUtil.hexDump(byteBuf) + "\n");
    }

    private byte[] integerTo2Bytes(int value) {
        byte[] result = new byte[2];
        result[0] = (byte) ((value >>> 8) & 0xFF);
        result[1] = (byte) (value & 0xFF);
        return result;
    }
}
